package com.cshuig.patterns.dataPool;

import java.util.Vector;

/**
 * Created by hogan on 2015/9/18.
 */
public class DatabasePoolFactory {

    private int poolsize = 10;
    private Vector<DatabaseConnect> pool;
    private static DatabasePoolFactory databasePoolFactory = new DatabasePoolFactory();

    /** 工厂类声明为一个单例类 */
    private DatabasePoolFactory() {
        pool = new Vector<>(poolsize);
        for (int i = 0; i < poolsize; i++) {
            pool.add(new DatabaseConnect("pool" + (i+1)));
        }
    }
    public static DatabasePoolFactory getInstance() {
        return databasePoolFactory;
    }

    public synchronized DatabaseConnect getDatapool() {
        if (pool.size() > 0) {
            DatabaseConnect connect = pool.get(0);
            pool.remove(connect);
            System.out.println(Thread.currentThread().getName() + " === " + System.currentTimeMillis() + " === 从连接池中取出一个pool, " + connect.toString());
            pooSize();
            return connect;
        } else {
            return null;
        }
    }

    public synchronized void releasePool(DatabaseConnect connect) {
        pool.add(connect);
        System.out.println(Thread.currentThread().getName() + " === " + System.currentTimeMillis() + " === 释放回一个pool, " + connect.toString());
        pooSize();
    }

    public synchronized void closeAllPool() {
        for (int i = 0; i < pool.size(); i++) {
            // 正常的数据库连接需要 调用 Connection.close()来关闭连接.
            pool.remove(i);
        }
    }

    public void pooSize() {
        System.out.println(Thread.currentThread().getName() + " === " + System.currentTimeMillis() + " === 剩下pool size = " + pool.size());
    }
}
